package vn.edu.saigontech.ncms.web.ajaxtags;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.ajaxtags.servlets.BaseAjaxServlet;
import net.sourceforge.ajaxtags.xml.AjaxXmlBuilder;

import org.hibernate.Session;
import org.hibernate.Transaction;

import vn.edu.saigontech.ncms.model.enumeration.TeacherType;
import vn.edu.saigontech.ncms.model.info.Teacher;
import vn.edu.saigontech.ncms.service.TeacherService;
import vn.edu.saigontech.ncms.util.Checker;
import vn.edu.saigontech.ncms.util.HibernateUtil;

@SuppressWarnings("serial")
public class TeacherTAServlet extends BaseAjaxServlet {
	@Override
	public String getXmlContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String teacherId = request.getParameter("teacherId");
		AjaxXmlBuilder xml = new AjaxXmlBuilder();
		Collection<Teacher> tas = new ArrayList<Teacher>();
		Session session = null;
		Transaction trans = null;
		try {
			session = HibernateUtil.getCurrentSession();
			trans = session.beginTransaction();
			Teacher teacher = TeacherService.INSTANCE.findById(Long.parseLong(teacherId));
			if(Checker.isNotNull(teacher)) {
				tas = TeacherService.INSTANCE.findActiveByTeacherType(TeacherType.TA);
			}
			trans.commit();
		}
		catch (NumberFormatException e) {
			// NOTHING TODO IS TODO S.THING
		} catch(Exception ex) {
			if(trans != null) {
				trans.rollback();
			}
			ex.printStackTrace();
		}
		finally {
			if(session != null) {
				session.close();
			}
		}
		xml.addItem("", true, "");
		for(Teacher teacher : tas) {
			xml.addItem(teacher.getFullName(), true, teacher.getId().toString());
		}
		return xml.toString();
	}
}
